<?php

require_once('Zend/Db/Table/Row/Abstract.php');

class Core_User_Validate
	extends Zend_Db_Table_Row_Abstract
{
	/**
	 * Password Validation Type
	 *
	 * @var string
	 */
	const TYPE_PASSWORD = 'PASSWORD';
	
	/**
	 * Registration Validation Type
	 *
	 * @var string
	 */
	const TYPE_REGISTER = 'REGISTER';

    /**
     * Name of the class of the Zend_Db_Table_Abstract object.
     *
     * @var string
     */
    protected $_tableClass = 'Zend_Db_Table';
    
	/**
	 * Private static reference to the validation table.
	 * 
     * @return Zend_Db_Table
	 */
	private static $table;

    /**
     * Table access method, for slightly more complex queries.
     *
     * @return Zend_Db_Table_Select
     */
    public static function getTableInstance()
    {
    	if ( empty(Core_User::$table ) )
    	{
    		Core_User_Validation::$table = new Zend_Db_Table('user_validate');
    		Core_User_Validation::$table->setRowClass('Core_User_Validation');
    	}
    	
    	return Core_User_Validation::$table;
    }
    
    /**
     * Factory method. Creates a new validation token based on the passed data.
     *
     * @param  array $config OPTIONAL Array of user-specified config options.
     * @return void
     * @throws Zend_Db_Table_Row_Exception
     */
    public static function factory( $user_id_or_token )
    {
    	$table = Core_User_Validation::getTableInstance();
    	
		if ( is_null($user_id_or_token) )
		{
			$row = $table->createRow(array(), Zend_Db_Table_Abstract::DEFAULT_DB);
		}
		else if ( is_int($user_id_or_token) )
		{
			$row = $table->fetchRow( $table->select()->where('userId=?',$user_id_or_token));
		}
		else
		{
			$row = $table->fetchRow( $table->select()->where('token=?',$user_id_or_token));
		}
			
		return $row;
    }
    
    /**
     * Is this expired.
     * 
     * @param int $timeout
     */
    public function isExpired( $timeout = 86400 )
    {
		// Make sure the token isn't expired.
		$validationCreated = strtotime($this->updated);
		$validationExpire = mktime() - $timeout;
		
		if ( $validationExpire > $validationCreated )
		{
			return true;
		}
		else
		{
			return false;
		}
    }
    
    /**
	 * @inheritDoc
     */
    protected function _doInsert()
    {
    	$this->created = new Zend_Db_Expr('NOW()');
    	$this->updated = new Zend_Db_Expr('NOW()');
    	
    	parent::_doInsert();
    }
    
    /**
	 * @inheritDoc
     */
    protected function _doUpdate()
    {
    	$this->updated = new Zend_Db_Expr('NOW()');
    	
    	parent::_doUpdate();
    }
}